package com.example.forum.controller;

import com.example.forum.domain.DiscussPost;
import com.example.forum.domain.Page;
import com.example.forum.domain.User;
import com.example.forum.service.DiscussPostService;
import com.example.forum.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;

    @RequestMapping({"/index","/"})
    public String index(Model model,
                        @RequestParam(value = "curPage",required = false,defaultValue = "1")int curPage,
                        @RequestParam(value = "pageSize",required = false,defaultValue = "10")int pageSize){
        List<DiscussPost> list = discussPostService.findAll("0", (curPage-1)*pageSize, pageSize);
        List<Map<String,Object>> discussPosts=new ArrayList<>();
        if(list!=null){
            for(DiscussPost discussPost:list){
                Map<String,Object> map=new HashMap<>();
                map.put("discussPost",discussPost);
                User user = userService.findById(Integer.parseInt(discussPost.getUserId()));
                map.put("user",user);
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts",discussPosts);
        Page page = discussPostService.findAllCount("0");
        page.setCurPage(curPage);
        model.addAttribute("page",page);
        return "index";
    }
}
